package cz.patamat.support;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailDataStorage {
	
	private InternetAddress ADMIN_EMAIL;	// sender of email
	private InternetAddress SUBSCRIBERS_STORAGE_EMAIL;	// all subscribers email address are stored as mails in this mail account
	private InternetAddress PROMOTIONANSWERSHEET_STORAGE_EMAIL;
	
	public EmailDataStorage() {
		try {
			ADMIN_EMAIL = new InternetAddress("master.patamat@gmail.com", "Pat a Mat project administrator");
			SUBSCRIBERS_STORAGE_EMAIL = new InternetAddress("subscribersstorage.patamat@gmail.com", "Subscribers storage");
			PROMOTIONANSWERSHEET_STORAGE_EMAIL = new InternetAddress("promotionanswersheet.patamat@gmail.com", "Promotion answer sheet storage");
		} catch (UnsupportedEncodingException e) {
			System.err.println("Unsupported encoding in admin email address");
			e.printStackTrace();
		}
	}
	
	public void saveSubscriber(String emailAddress) {
		String msgSubject = "Pat a Mat, subscriber registration";
		String msgBody = "Subscriber email: " + emailAddress;		
		
		sendMail(msgSubject, msgBody, SUBSCRIBERS_STORAGE_EMAIL);
	}
	
	public void saveAnswerSheetResponse(String answerSheetResponse) {
		String msgSubject = "Pat a Mat, answer sheer response";
		String msgBody = answerSheetResponse;		
		
		sendMail(msgSubject, msgBody, PROMOTIONANSWERSHEET_STORAGE_EMAIL);
	}
	
	private void sendMail(String subject, String body, InternetAddress sendTo) {
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);        
        try {
        	Message msg = new MimeMessage(session);
            msg.setFrom(ADMIN_EMAIL);
            msg.addRecipient(Message.RecipientType.TO, sendTo);
            msg.setSubject(subject);
            msg.setText(body);
            Transport.send(msg);
        } catch (AddressException e) {
            System.err.print("Address exception during subscribtion saving.");
            e.printStackTrace();
        } catch (MessagingException e) {
        	System.err.print("Messagging exception during subscribtion saving");
            e.printStackTrace();
        }
	}

}
